//
//  JPStatusDAL.swift
//  JPWeibo
//
//  Created by 哇咔咔 on 2016/10/10.
//  Copyright © 2016年 jp. All rights reserved.
//

import UIKit
import SDWebImage

let MaxTimeinterval: TimeInterval = 7 * 24 * 3600


class JPStatusDAL: NSObject {
    
    class func loadData(sinceId: Int64, maxId: Int64, callBack: @escaping ([[String: Any]])->()) {
        
        let localArray = checkCacheData(sinceId: sinceId, maxId: maxId)
        if localArray.count > 0 {
            callBack(localArray)
            return
        }
        
        JPNetworkTool.sharedNetworkTool.requestStatus(accessToken: (JPUserInfoModel.decodeUserInfo()?.access_token)!, sinceId: sinceId, maxId: maxId) { (response, error) in
            
            if error != nil {
                return
            }
            
            guard let dict = response as? [String: Any] else {
                return
            }
            
            guard let statusArr = dict["statuses"] as? [[String: Any]] else {
                return
            }
        
            cacheData(statusDicArray: statusArr)
            callBack(statusArr)
            
        }
    }
    
    //  查询缓存数据是否有需要的数据
    class private func checkCacheData(sinceId: Int64, maxId: Int64) -> [[String: Any]] {
        var sql = "SELECT * FROM statuses\n"
        
        if maxId > 0 {
            sql += "where statusid < \(maxId)\n"
        }else {
            sql += "where statusid > \(sinceId)\n"
        }
        
        sql += "and userid = \(JPUserInfoViewModel.sharedUserInfoViewModel.userInfo!.uid)\n"
        sql += "order by statusid desc\n"
        sql += "limit 20\n"
        
        let dicArray = SqliteManager.sharedManager.selectedDicArray(sql: sql)
        
        var tempArray = [[String: Any]]()
        
        for dic in dicArray {
            let statusData = dic["status"] as! Data
            
            let status = try! JSONSerialization.jsonObject(with: statusData, options: [])
            tempArray.append(status as! [String : Any])
        }
        
        return tempArray
    }
    
    //  将数据存储到数据库
    static func cacheData(statusDicArray: [[String: Any]]) {
        let sql = "INSERT OR REPLACE INTO Statuses(statusid, status, userid) VALUES(?, ?, ?)"
        
        let userid = JPUserInfoViewModel.sharedUserInfoViewModel.userInfo?.uid
        SqliteManager.sharedManager.queue.inTransaction { (db, rollback) in
            
            for statusDic in statusDicArray {
                let statusid = statusDic["id"]
                let statusData = try! JSONSerialization.data(withJSONObject: statusDic, options: [])
                let result = db?.executeUpdate(sql, withArgumentsIn: [userid, statusid, statusData])
                
                if result == false {
                    rollback?.pointee = true
                    break
                }
            }
        }
    }
    
    // 删除7天前的缓存数据
    
    static func deleteCache() {
        let deleteDate = Date().addingTimeInterval(-MaxTimeinterval)
        
        let dt = DateFormatter()
        dt.dateFormat = "yyyy:MM:dd HH:mm:ss"
        dt.locale = Locale(identifier: "en_US")
        
        let dateString = dt.string(from: deleteDate)
        
        let sql = "DELETE FROM Statuses where time < '\(dateString)"
        
        SqliteManager.sharedManager.queue.inDatabase { (db) in
            let result = db?.executeUpdate(sql, withArgumentsIn: nil)
            
            if result == true {
                print("删除数据成功")
            }else {
                print("删除数据失败")
            }
        }
        
    }

}
